<template>
  <div>
    <slot name="research"></slot>
    <el-table class="tableClass" ref="elTable" :data="list" v-loading="tableLoading" v-bind="tableProps"
      @current-change="currentChange" @row-click="rowClick" @expand-change="expandChange"
      @selection-change='selectionChange' header-cell-class-name="headerClass-row" @header-dragend="headerDragend"
      @cell-dblclick="cellDblclick" :cell-style="tableCellStyle">
      <el-table-column v-if="tableProps.selection && tableProps.selection.showSelection"
        v-bind="tableProps.selection.props" type="selection" :width="tableProps.indexColWidth||55">
      </el-table-column>
      <el-table-column v-if="tableProps.expandable" type="expand">
        <template slot-scope="props">
          <slot name="expand-area" v-bind="{row:props.row,$index:props.$index}">
            <span class="m-5">这是展开行插槽</span>
          </slot>
        </template>
      </el-table-column>
      <el-table-column fixed='left' v-if="tableProps.showIndexCol" type="index" label="No." :index="indexMethod"
        :width="tableProps.indexColWidth||50">
      </el-table-column>
      <el-table-column v-for="(item, index) in columns" :key="index" :show-overflow-tooltip='!item.hideTooltip'
        :label="item.title || item.key" :prop="item.key" v-bind="item">
        <template v-slot:header="scope">
          <slot name="header" v-bind="scope">
            <div>{{item.title}}</div>
          </slot>
        </template>
        <template slot-scope="scope">
          <!--##########这里可以根据key自定义列##########-->
          <template v-if="item.isEdit && isEditCell(scope,item)">
            <el-input size="mini" v-model="scope.row[item.key]" @blur="initEditCellId(scope,$event)"
              @keyup.enter.native="inputBlur" class="tab-inp-max"></el-input>
          </template>
          <template v-else>
            <slot name="content" v-bind="{row:scope.row,key:item.key}">
              <span>{{scope.row[item.key]}}</span>
            </slot>
          </template>
        </template>
      </el-table-column>
      <el-table-column v-if="!tableProps.hideOperations" :resizable="false" :width="tableProps.opsColWith||100"
        fixed="right">
        <template slot="header" slot-scope="">
          <slot name="operation-title">
            <span>操作</span>
          </slot>
        </template>
        <template slot-scope="scope">
          <div class="flex-justify-content">
            <slot name="operation" v-bind="{row:scope.row,$index:scope.$index}">
              <a href="#" class="text-blue" v-permission="subassemblyName +'.edit'"
                @click.prevent.stop="editItem(scope.row,scope.$index)">编辑</a>
              <a style="margin-left:5px;" href="#" class="text-red" v-permission=" subassemblyName +'.delete'"
                @click.prevent.stop="deleteItem(scope.row,scope.$index)">删除</a>
            </slot>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
function defineNonEnumKey(obj, key, value) {
  Object.defineProperty(obj, key, {
    value: value,
    writable: true,
    enumerable: false,
  })
  return obj
}
export default {
  name: 'z-table',
  props: {
    tableLoading: { type: Boolean, default: false },
    list: { type: Array, default: null },
    tableProps: {
      type: Object,
      default: {
        border: true,
        opsColWith: 80,
      },
    },
    // query: {
    //   type: Object,
    //   default: {
    //     size: 10,
    //     page: 1,
    //   },
    // },
    columns: { type: Array, default: null },
  },
  data() {
    return {
      subassemblyName: null,
      editCellId: '',
      cellData: {},
    }
  },
  created() {
    this.subassemblyName = this.$route.name
  },
  methods: {
    indexMethod(index) {
      // return index + 1 + (this.query.page - 1) * this.query.size
      return index + 1
    },
    currentChange(row) {
      this.$emit('current-change', row)
    },
    rowClick(row) {
      this.$emit('row-click', row)
    },
    editItem(r, i) {
      this.$emit('editItem', r, i)
    },
    deleteItem(r, i) {
      this.$emit('deleteItem', r, i)
    },
    expandChange(row, expandRowKeys) {
      this.$emit('expand-change', row, expandRowKeys)
    },
    selectionChange(val) {
      this.$emit('selection-change', val)
    },
    headerDragend(newWidth, oldWidth, column, event) {
      this.$emit('header-dragend', { newWidth, oldWidth, column, event })
    },
    cellDblclick(row, column, cell) {
      this.editCellId = row.$_rowKey + '_' + column.property
      this.cellData = _.cloneDeep(row)
      this.$nextTick(() => {
        if (cell.querySelector('input')) {
          cell.querySelector('input').focus()
        }
      })
    },
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (!row['$_rowKey']) {
        row['$_rowKey'] = 'row_' + rowIndex
        defineNonEnumKey(row, '$_rowKey', row['$_rowKey'])
      }
      return ['cell-style', 'cellStyle'].reduce((prev, item) => {
        let v = this.tableProps[item]
        if (v) {
          prev = _.isFunction(v) ? v({ row, column, rowIndex, columnIndex }) : v
        }
        return prev
      }, null)

      // if (this.tableProps['cell-style']) {
      //   return _.isFunction(this.tableProps['cell-style'])
      //     ? this.tableProps['cell-style']({ row, column, rowIndex, columnIndex })
      //     : this.tableProps['cell-style']
      // }
      // if (this.tableProps['cellStyle']) {
      //   return _.isFunction(this.tableProps['cellStyle'])
      //     ? this.tableProps['cellStyle']({ row, column, rowIndex, columnIndex })
      //     : this.tableProps['cellStyle']
      // }
    },
    isEditCell(scope, item) {
      return this.editCellId === scope.row['$_rowKey'] + '_' + scope.column.property
    },
    inputBlur(e) {
      //防止触发两次  （回车也会触发失去焦点）
      e.target.blur()
    },
    initEditCellId(scope) {
      let key = scope.column.property
      this.editCellId = ''
      if (
        this.cellData[key] === scope.row[key] ||
        ((this.cellData[key] === null || this.cellData[key] === undefined) && !scope.row[key])
      ) {
        return
      }
      this.$emit('updateCell', {
        index: scope.$index,
        key,
        rowOldData: this.cellData,
        rowData: scope.row,
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.flex-justify-content {
  display: flex;
  justify-content: space-around;
}
.tableClass {
  ::v-deep .el-table__fixed,
  ::v-deep .el-table__fixed-right {
    height: 100% !important; //设置高优先，以覆盖内联样式
  }
}
::v-deep .tab-inp-max {
  input {
    height: 23px;
  }
}
</style>
